<template>
  <div class="container">
    <div class="app-container">
      <el-card>
        <!-- 角色管理内容 -->
        <div class="role-operate">
          <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
        </div>
        <!-- 放置table组件 -->
        <el-table :data="list" :border="true">
          <!-- 放置列 -->
          <el-table-column label="序号" type="index" width="50">
            <template slot-scope="scope">{{ (pageParams.pageNumber - 1) * pageParams.pageSize + scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column prop="name" width="200" label="角色">
            <template v-slot="{ row }">
              <!-- 条件判断 -->
              <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
              <span v-else>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述">
            <template v-slot="{ row }">
              <el-input v-if="row.isEdit" v-model="row.editRow.desc" size="mini" type="textarea" />
              <span v-else>{{ row.desc }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <!-- 放置操作按钮 -->
            <template v-slot="{ row }">
              <template v-if="row.isEdit">
                <!-- 编辑状态 -->
                <el-button type="primary" size="mini" @click="btnEditOK(row)">确定</el-button>
                <el-button size="mini" @click="row.isEdit = false">取消</el-button>
              </template>
              <template v-else>
                <!-- 非编辑状态 -->
                <el-button type="text" @click="btnPermission(row.id)">分配权限</el-button>
                <el-button type="text" @click="btnEditRow(row)">编辑</el-button>
                <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="confirmDel(row.id)">
                  <el-button slot="reference" style="margin-left: 10px" type="text">删除</el-button>
                </el-popconfirm>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <!-- 放置分页组件 -->
        <el-row type="flex" style="margin: 40px 0" align="middle" justify="center">
          <!-- 放置分页组件 -->
          <el-pagination
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageParams.pageSize"
            :current-page="pageParams.pageNumber"
            :total="pageParams.total"
            layout="total, sizes, prev, pager, next"
            @current-change="changePage"
            @size-change="sizeChange"
          />
        </el-row>
      </el-card>
    </div>

    <!-- 放置弹层 -->
    <el-dialog width="600px" title="新增角色" :visible.sync="showDialog" @close="btnCancel">
      <!-- 表单内容 -->
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width: 300px" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="roleForm.desc" type="textarea" :rows="3" style="width: 300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 放置权限弹层 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <!-- 放置权限数据 -->
      <el-checkbox-group v-model="checkList">
        <el-checkbox :label="item" v-for="item in permissionList" :key="item"></el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { roleListAPI, permissionLisAPI, getRolePermissionsAPI, updateRolePermissionsAPI, updateRoleAPI, addRole,deleteRolePermissionsAPI } from '@/api/user'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      permissionObject: [], // 中转数组对象
      permissionList: [], // 系统所有权限点
      checkList: [], // 某个用户的权限点
      permissionIds: [], //权限点对应的id
      showDialog: false, // 控制弹层显示隐藏
      roleId: 0,
      // 将分页信息放置到一个对象中
      pageParams: {
        pageNumber: 1, // 第几页
        pageSize: 5, // 每页多少条
        total: 0
      },
      roleForm: {
        name: '',
        desc: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      showPermissionDialog: false,
      permissionData: [],
      activeName: 'roleManage'
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // tab点击切换
    handleClick(tab, event) {
      console.log(tab, event)
    },
    async getRoleList() {
      const { data, total } = await roleListAPI(this.pageParams)
      this.list = data // 赋值数据
      this.pageParams.total = total
      // 针对每一行数据添加一个编辑标记
      this.list.forEach(item => {
        // item.isEdit = false // 添加一个属性 初始值为false
        // 数据响应式的问题  数据变化 视图更新
        // 添加的动态属性 不具备响应式特点
        // this.$set(目标对象, 属性名称, 初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          desc: item.desc
        })
      })
    },
    // 切换分页时 请求新的数据
    changePage(newPage) {
      this.pageParams.pageNumber = newPage // 赋值当前页码
      this.getRoleList()
    },
    btnOK() {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          await addRole({ ...this.roleForm })
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.$refs.roleForm.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    // 点击编辑行
    btnEditRow(row) {
      row.isEdit = true // 改变行的编辑状态
      // 更新缓存数据
      row.editRow.name = row.name
      row.editRow.desc = row.desc
    },
    // 点击确定时触发
    async btnEditOK(row) {
      if (row.editRow.name && row.editRow.desc) {
        // 下一步操作
        await updateRoleAPI({ ...row.editRow, id: row.id })
        // 更新成功
        this.$message.success('更新角色成功')
        // 更新显示数据  退出编辑状态
        // row.name = row.editRow.name // eslint的一校验 误判
        // Object.assign(target, source)
        Object.assign(row, {
          ...row.editRow,
          isEdit: false // 退出编辑模式
        }) // 规避eslint的误判
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    // 点击了确定触发的
    async confirmDel(id) {
      await deleteRolePermissionsAPI({id}) // 后端删除
      this.$message.success('删除角色成功')
      // 删除的如果是最后一个
      if (this.list.length === 1) this.pageParams.page--
      this.getRoleList()
    },
    async btnPermission(id) {
      this.roleId = id
      // 系统全部权限点
      const res = await permissionLisAPI()
      this.permissionList = res.data.map(i => i.desc)
      this.permissionObject = res.data
      // 当前用户权限点
      const res2 = await getRolePermissionsAPI(id)
      this.showPermissionDialog = true
      if (res2.data.length > 0) {
        this.checkList = res2.data.map(i => i.desc)
      }
    },
    // 点击确定时触发
    async btnPermissionOK() {
      const res = await updateRolePermissionsAPI({ id: this.roleId, permissionIds: this.permissionIds })
      this.$message.success(res.message)
      this.showPermissionDialog = false
      this.getRoleList()
    },
    // 页面大小改变
    sizeChange(value) {
      this.pageParams.pageSize = value
      this.getRoleList()
    }
  },
  watch: {
    checkList(values) {
      this.checkList = values
      this.permissionIds = []
      this.permissionObject.forEach(i => {
        this.checkList.forEach(j => {
          if (j === i.desc && !this.permissionIds.includes(i.id)) {
            this.permissionIds.push(i.id)
          }
        })
      })
    }
  }
}
</script>
<style scoped lang="scss">
.role-operate {
  padding: 0 0 10px;
}

.container {
  .app-container {
    padding: 20px;
  }
}
</style>
